import { ApiResponse, LoginForm, Token } from '@/types/data'
import { LoginAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage'

export const login = (data: LoginForm): RootThunkAction => {
//   console.log(data)
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>('/authorizations', data)
    // res.data中保存的是后端给我们的真实数据
    // console.log(res) // refresh_token, token

    // 保存本地（持久化）
    setToken(res.data.data)

    // 保存到redux
    dispatch({
      type: 'login/token',
      payload: res.data.data
    })
  }
}

export const logout = (): LoginAction => {
  // 清空保存本地（持久化）
  removeToken()
  // 清空redux
  return {
    type: 'login/removetoken'
  }
}
export const getCode = (mobile: string) => {
  return async () => {
    await request.get(`/sms/codes/${mobile}`)
  }
}
